import java.io.FileNotFoundException;
import java.io.IOException;


// class VMexecutor is a THREAD for parralel processing 
public class VMExecutor implements Runnable {
	
	// Thread
	Thread t;
	// This thread is around a virtual machine
	private VirtualMachine VM;
	// Thread ID (for internal organization)
	private String threadId;
	// calculated value (default -1, to check if it is finished)
	private Integer value;
	// file to be processed
	private String file;
	
	// constructor, using a VM and a file
	public VMExecutor(VirtualMachine m, String file) {
		// saving the virtual machine locally
		this.VM = m;
		// creating a thread
		this.threadId = ("VM_"+Math.random()).substring(5, 10);
		// set default value to -1 so it can be checked whether the virtual machine is finished
		this.value = -1;
		this.file = file;
		
		// create thread (runs run())
		this.t = new Thread(this, this.threadId);
		this.t.start();
		
	}

	// function executed when the thread is started
	@Override
	public void run() {
		try {
			// count the vowels in the file
			this.value = this.countWords(file);
		} catch (FileNotFoundException e) {
			System.out.println("Something went wrong with sending the file to the VM. File not found on VM.");
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("Something went wrong with reading the file on the VM");
			e.printStackTrace();
		}
	}

	// let the VM count the files vowels
	public int countWords(String file) throws FileNotFoundException, IOException {
		return this.VM.countWords(file);
	}
	
	// returns the counted value
	public int getValue() {
		return this.value;
	}

}
